#pragma once

#include <iostream>
#include <cstdio>
#include <pthread.h>
#include <functional>
#include <unistd.h>
#include <cstdlib>

using namespace std;

class Thread
{
    typedef void *(*prun)(void *);
    typedef enum
    {
        FREE,
        RUNNING,
        EXITED
    } status;

public:
    // 创建线程时，传入线程编号、线程函数、传入线程函数的参数
    Thread(int index, prun func, void *arg) : _index(index), _func(func), _arg(arg)
    {
        char name[64] = {0};
        snprintf(name, sizeof(name), "thread-%d", index);
        _name = name;
        _stat = FREE;
    }

    pthread_t getTid()
    {
        return _tid;
    }

    string getName()
    {
        return _name;
    }

    void run()
    {
        int ret = pthread_create(&_tid, nullptr, _func, _arg);
        if (ret != 0)
            exit(1);
        _stat = RUNNING;
    }

    void join()
    {
        int ret = pthread_join(_tid, nullptr);
        if (ret != 0)
            exit(1);
        _stat = EXITED;
    }

public:
    pthread_t _tid;
    string _name;
    prun _func;
    void *_arg;
    int _index;
    status _stat;
};